package com.ubing.boot.notesforjava.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;



/**
 * 功能描述：请求拦截
 * 主要用于打印请求日志和响应日志
 *
 * @param
 * @author ubing
 * @date 2023/2/15 21:32
 * @return
 * @修改日志： ubing 2023/2/15 21:32 条件装配
 */
@Component
@Aspect
@Slf4j  // 日志打印注解
@ConditionalOnProperty(prefix = "aop.request", name = "enable", havingValue = "true") // 条件装配配置是否打开此aop
public class RequestAspect {

    @Pointcut("execution(public * com.ubing.boot.notesforjava.controller.*.*(..))")
    public void requestAspect() {
    }

    @Around("requestAspect()")
    public Object requestPointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        long s1 = System.currentTimeMillis();
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
//        String uuid = IdUtil.randomUUID();
        // IP
        String ip = request.getRemoteAddr();
        // 获取请求方法
        String url = request.getRequestURI();
        // 获取请求方式
        String method = request.getMethod();
        //请求数据
        String reqData = request.getQueryString();

        //请求时间

        Date reqDate = new Date();
//        Date reqDate = (Date) time;
        log.info("\r\n------请求明细 START------\r\n请求时间: {}\r\nIP: {}\r\n请求API地址: {}\r\n请求方式: {}\r\nURI查询参数: {}\r\n------请求明细 END------", reqDate, ip, url, method, reqData);

        // 获取响应数据
        Object result = joinPoint.proceed();
        // 响应时间
//        reqDate = DateUtil.now();
        reqDate = new Date();
        long s2 = System.currentTimeMillis();
        log.info("\r\n------响应明细 START------\r\n响应时间: {}\r\n耗时: {}毫秒\r\n------响应明细 END------", reqDate, (s2 - s1));
        return result;
    }
}